"""
创建默认管理员用户的脚本
"""
import asyncio
from motor.motor_asyncio import AsyncIOMotorClient
from app.core.config import settings
from app.core.security import get_password_hash
from app.core.permissions import get_permissions_for_role
from app.models.user import UserRole, UserStatus
from datetime import datetime

async def create_admin_user():
    """创建默认管理员用户"""
    # 连接数据库
    client = AsyncIOMotorClient(settings.MONGODB_URL)
    db = client[settings.MONGODB_DATABASE]
    
    try:
        # 删除现有的管理员用户（如果存在）
        await db.users.delete_many({"email": "admin@example.com"})
        await db.users.delete_many({"name": "admin"})
        print("已删除现有的admin用户")
        
        # 创建管理员用户
        admin_user = {
            "username": "admin",  # 支持用户名登录
            "name": "admin",  # 真实姓名，不支持登录
            "email": "admin@example.com",  # 支持邮箱登录
            "hashed_password": get_password_hash("123456"),  # 修改密码为123456
            "status": UserStatus.ACTIVE,
            "is_verified": True,
            "roles": [UserRole.ADMIN],
            "permissions": get_permissions_for_role(UserRole.ADMIN),
            "department": "IT",
            "position": "System Administrator",
            "created_at": datetime.utcnow(),
            "updated_at": datetime.utcnow(),
            "login_count": 0
        }
        
        # 插入数据库
        result = await db.users.insert_one(admin_user)
        print(f"管理员用户创建成功，ID: {result.inserted_id}")
        print("登录信息:")
        print("用户名: admin")
        print("邮箱: admin@example.com")
        print("密码: 123456")
        print("状态: 激活且已验证")
        print("角色: 管理员")
        
        # 创建测试用户
        await db.users.delete_many({"email": "test@example.com"})
        test_user = {
            "name": "user",  # 支持用户名登录
            "email": "test@example.com",
            "hashed_password": get_password_hash("123456"),  # 统一密码为123456
            "status": UserStatus.ACTIVE,
            "is_verified": True,
            "roles": [UserRole.DEVELOPER],
            "permissions": get_permissions_for_role(UserRole.DEVELOPER),
            "department": "Development",
            "position": "Developer",
            "created_at": datetime.utcnow(),
            "updated_at": datetime.utcnow(),
            "login_count": 0
        }
        
        result = await db.users.insert_one(test_user)
        print(f"测试用户创建成功，ID: {result.inserted_id}")
        print("登录信息:")
        print("用户名: user")
        print("邮箱: test@example.com")
        print("密码: 123456")
        
        # 创建一个被禁用的用户用于测试
        await db.users.delete_many({"email": "disabled@example.com"})
        disabled_user = {
            "name": "disabled",
            "email": "disabled@example.com",
            "hashed_password": get_password_hash("123456"),
            "status": UserStatus.INACTIVE,  # 被禁用状态
            "is_verified": True,
            "roles": [UserRole.DEVELOPER],
            "permissions": get_permissions_for_role(UserRole.DEVELOPER),
            "department": "Development",
            "position": "Developer",
            "created_at": datetime.utcnow(),
            "updated_at": datetime.utcnow(),
            "login_count": 0
        }
        
        result = await db.users.insert_one(disabled_user)
        print(f"禁用用户创建成功，ID: {result.inserted_id}")
        print("登录信息:")
        print("用户名: disabled")
        print("邮箱: disabled@example.com")
        print("密码: 123456")
        print("状态: 已禁用")
        
        # 创建一个未验证的用户用于测试
        await db.users.delete_many({"email": "unverified@example.com"})
        unverified_user = {
            "name": "unverified",
            "email": "unverified@example.com",
            "hashed_password": get_password_hash("123456"),
            "status": UserStatus.ACTIVE,
            "is_verified": False,  # 未验证状态
            "roles": [UserRole.DEVELOPER],
            "permissions": get_permissions_for_role(UserRole.DEVELOPER),
            "department": "Development",
            "position": "Developer",
            "created_at": datetime.utcnow(),
            "updated_at": datetime.utcnow(),
            "login_count": 0
        }
        
        result = await db.users.insert_one(unverified_user)
        print(f"未验证用户创建成功，ID: {result.inserted_id}")
        print("登录信息:")
        print("用户名: unverified")
        print("邮箱: unverified@example.com")
        print("密码: 123456")
        print("状态: 未验证")
        
        print("\n=== 用户创建完成 ===")
        print("所有测试用户密码统一为: 123456")
        print("可用于测试不同登录场景:")
        print("1. 正常登录: admin/admin@example.com")
        print("2. 普通用户: user/test@example.com")
        print("3. 账户被禁用: disabled/disabled@example.com")
        print("4. 账户未验证: unverified/unverified@example.com")
        
    except Exception as e:
        print(f"创建用户失败: {e}")
        import traceback
        traceback.print_exc()
    finally:
        client.close()

if __name__ == "__main__":
    asyncio.run(create_admin_user())